package com.kefu.call.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.basic.mapper.BasicTagMapper;
import com.kefu.basic.model.BasicTag;
import com.kefu.call.mapper.CallMakeCallMapper;
import com.kefu.call.mapper.CallStartMapper;
import com.kefu.call.model.CallMakeCall;
import com.kefu.call.model.CallStart;
import com.kefu.call.model.CallTagRel;
import com.kefu.call.vo.CallTagRelInsertVo;
import com.kefu.common.service.AbstractKefuService;
import com.kefu.common.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CallTagRelService extends AbstractKefuService<CallTagRel> {
    @Resource
    private BasicTagMapper basicTagMapper;
    @Resource
    private CallStartMapper callStartMapper;
    @Resource
    private CallMakeCallMapper callMakeCallMapper;


    public CallStart addInTag(CallTagRelInsertVo callTagRelVo) {
        List<CallStart> callStarts = callStartMapper.selectList(
                Wrappers.lambdaQuery(CallStart.class)
                .eq(CallStart::getCallId, callTagRelVo.getCallId()));
        Assert.isEmpty(callStarts, "呼入数据不存在！");
        CallStart callStart = callStarts.get(0);
        delete(Wrappers.lambdaQuery(CallTagRel.class).eq(CallTagRel::getCallId, callTagRelVo.getCallId()));
        List<CallTagRel> callTagRels =
                callTagRelVo.tagConvert(callTagRelVo.getCallId());
        if (CollUtil.isNotEmpty(callTagRels)) {
            save(callTagRels);
            logger.info("批量给呼入通话打标签:{}", callTagRels);
        }
        List<BasicTag> basicTags = basicTagMapper.selectList(Wrappers.lambdaQuery(BasicTag.class)
                .in(BasicTag::getTagId, callTagRelVo.getBasicTags()));
        callStart.setBasicTag(basicTags);
        return callStart;
    }

    public CallMakeCall addOutTag(CallTagRelInsertVo callTagRelVo) {
        List<CallMakeCall> callMakeCalls = callMakeCallMapper.selectList(
                Wrappers.lambdaQuery(CallMakeCall.class)
                .eq(CallMakeCall::getCallId, callTagRelVo.getCallId()));
        Assert.isEmpty(callMakeCalls, "外呼数据异常！");
        CallMakeCall callMakeCall = callMakeCalls.get(0);
        delete(Wrappers.lambdaQuery(CallTagRel.class).eq(CallTagRel::getCallId, callTagRelVo.getCallId()));
        List<CallTagRel> callTagRels =
                callTagRelVo.tagConvert(callTagRelVo.getCallId());
        if (CollUtil.isNotEmpty(callTagRels)) {
            save(callTagRels);
            logger.info("批量给呼出通话打标签:{}", callTagRels);
        }
        List<BasicTag> basicTags = basicTagMapper.selectList(Wrappers.lambdaQuery(BasicTag.class)
                .in(BasicTag::getTagId, callTagRelVo.getBasicTags()));
        callMakeCall.setBasicTag(basicTags);
        return callMakeCall;
    }
}
